<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import { GetFileUploadStatusApi } from '@/api/table'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ElMessage, ElUpload, ElIcon, FormRules, ElMessageBox } from 'element-plus'
import { Search } from '@/components/Search'
import { ContentWrap } from '@/components/ContentWrap'
import { BaseButton } from '@/components/Button'
import { Dialog } from '@/components/Dialog'
import { useValidator } from '@/hooks/web/useValidator'
import { useForm } from '@/hooks/web/useForm'
import { Form, FormSchema } from '@/components/Form'
import * as XLSX from 'xlsx'
import { useButtonPermiss } from '@/utils/buttonpermiss'
const { t } = useI18n()
const haspermiss = ref<String[]>([])
const getUseButtonPermiss = () => {
  useButtonPermiss().then((res) => {
    haspermiss.value = res
  })
}
getUseButtonPermiss()
let list: sysField[] = []
const { required } = useValidator()
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await GetFileUploadStatusApi({
      pageNo: unref(currentPage),
      pageRow: unref(pageSize),
      pageModel: { ...unref(searchParams) }
    })
    list = res.data.pageModels || []

    return {
      list: list,
      total: res.data.totalCount
    }
  }
})

const { dataList, loading, total, pageSize, currentPage } = tableState
const { getList } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('userDemo.index'),
    type: 'index'
  },
  {
    field: 'stationNo',
    label: '采集站编号',
    sortable: true
  },
  {
    field: 'stationName',
    label: '采集站',
    sortable: true
  },
  {
    field: 'depName',
    label: '部门',
    sortable: true
  },
  {
    field: 'userName',
    label: '用户',
    sortable: true
  },
  {
    field: 'deviceNo',
    label: '设备编号',
    sortable: true
  },
  {
    field: 'fileName',
    label: '文件名称',
    width: 280
  },
  {
    field: 'fileTime',
    label: '拍摄时间',
    sortable: true,
    width: 180
  },
  {
    field: 'uploadFileTime',
    label: '上传时间',
    sortable: true,
    width: 180
  },
  {
    field: 'uploadStatus',
    label: '上传状态',
    slots: {
      default: (data) => {
        return (
          <>
            {data.row.uploadStatus == 0
              ? '上传中'
              : data.row.uploadStatus == 1
                ? '上传完成'
                : '上传失败'}
          </>
        )
      }
    }
  },

  {
    field: 'avgSpeed',
    label: '上传速度(MB/s)'
  },
  {
    field: 'uploadErrorMsg',
    label: '错误信息'
  }
])

interface sysField {
  stationNo: string
  stationName: string
  depNo: string
  depName: string
  userNo: string
  userName: string
  deviceNo: string
  fileName: string
  fileTime: string
  uploadFileTime: string
  uploadStatus: number
  avgSpeed: string
  uploadErrorMsg: string
}
interface userExport {
  采集站编号: string
  采集站: string
  部门编号: string
  部门名称: string
  用户编号: string
  用户名: string
  设备编号: string
  文件名称: string
  拍摄时间: string
  上传时间: string
  上传状态: string
  '上传速度(MB/s)': string
  错误信息: string
}

const handleData = () => {
  let arr: userExport[] = []
  list.map((item) => {
    arr.push({
      采集站编号: item.stationNo,
      采集站: item.stationName,
      部门编号: item.depNo,
      部门名称: item.depName,
      用户编号: item.userNo,
      用户名: item.userName,
      设备编号: item.deviceNo,
      文件名称: item.fileName,
      拍摄时间: item.fileTime,
      上传时间: item.uploadFileTime,
      上传状态:
        item.uploadStatus == 0 ? '上传中' : item.uploadStatus == 1 ? '上传完成' : '上传失败',
      '上传速度(MB/s)': item.avgSpeed,
      错误信息: item.uploadErrorMsg
    })
  })
  return arr
}
const exportToExcel = () => {
  // 创建一个工作簿
  const workbook = XLSX.utils.book_new()
  // 创建一个工作表
  const worksheet = XLSX.utils.json_to_sheet(handleData())

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

  // 生成Excel文件
  XLSX.writeFile(workbook, '用户列表.xlsx')
}
const searchSchema = reactive<FormSchema[]>([
  {
    field: 'depName',
    label: '部门',
    component: 'Input'
  },
  {
    field: 'userName',
    label: '用户',
    component: 'Input'
  },
  {
    field: 'fileName',
    label: '文件名称',
    component: 'Input'
  },
  {
    field: 'deviceNo',
    label: '设备编号',
    component: 'Input'
  },
  {
    field: 'uploadStatus',
    label: '上传状态',
    component: 'Select',
    componentProps: {
      placeholder: '请选择'
    },
    optionApi: async () => {
      return [
        { label: '上传完成', value: 1 },
        { label: '上传中', value: 0 },
        { label: '上传失败', value: -1 }
      ]
    }
  },

  {
    field: 'date',
    label: t('problem.time'),
    component: 'DatePicker',
    componentProps: {
      style: { width: '340px' },
      type: 'datetimerange',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      StartPlaceholder: 'Start date',
      EndPlaceholder: 'End date'
    }
  }
])

const searchParams = ref({})
const setSearchParams = (params: any) => {
  if (params.date) {
    params.startTime = params.date[0]
    params.endTime = params.date[1]
    delete params.date
  }
  searchParams.value = params
  getList()
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <BaseButton type="primary" @click="exportToExcel" v-if="haspermiss.includes('导出')">{{
      t('exampleDemo.exprot')
    }}</BaseButton>
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :reserveIndex="true"
      :columns="tableColumns"
      default-expand-all
      node-key="id"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      :showAction="true"
      @register="tableRegister"
    />
  </ContentWrap>
</template>
